package com.product.android.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.text.format.DateFormat;

import com.common.android.utils.FormatUtils;
import com.common.android.utils.StringUtils;
import com.nd.android.u.allcommon.R;
import com.product.android.business.ApplicationVariable;
/**
 * 时间相关类
 * <br>Created 2014-8-25 下午9:27:29
 * @version  
 * @author   huangyx		
 * @see 	 
 * Copyright(c) 2009-2014, TQ Digital Entertainment, All Rights Reserved
 */
@SuppressLint("SimpleDateFormat")
public class TimeUtils {
	private static final String TAG = "TimeUtils";
	private static final SimpleDateFormat todayRecentSdf = new SimpleDateFormat("今天HH:mm");
	private static final SimpleDateFormat yesterdayRecentSdf = new SimpleDateFormat("昨天HH:mm");
	private static final SimpleDateFormat beforeYesterDayRecentSdf = new SimpleDateFormat("前天HH:mm");
	private static final SimpleDateFormat otherRecentSdf = new SimpleDateFormat("MM-dd HH:mm");
	private static final SimpleDateFormat otherChatSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	private static final SimpleDateFormat monthformat = new SimpleDateFormat( "MM-dd" );
	
	public final static SimpleDateFormat DB_DATE_FORMATTER =
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    
	public final static SimpleDateFormat DATE_FORMATTER_YMD = 
            new SimpleDateFormat("yyyy年MM月dd日");
    
    //Wed Dec 15 02:53:36 +0000 2010
    public static final SimpleDateFormat TWITTER_DATE_FORMATTER = 
            new SimpleDateFormat("E MMM d HH:mm:ss Z yyyy", Locale.US);
    
    // Wed 15 Dec 02:53:36 +0000 2010
    public static final SimpleDateFormat TWITTER_SEARCH_API_DATE_FORMATTER = 
            new SimpleDateFormat("E, d MMM yyyy HH:mm:ss Z", Locale.US); 
    
    public static final long ONEDAY_SECONDSMillis = 86400000l;
    
    // 匹配服务端的生日格式，例如20130101
    public final static SimpleDateFormat BIRTHDATE_FORMATTER = 
            new SimpleDateFormat("yyyyMMdd");
    
    public static final SimpleDateFormat AGO_FULL_DATE_FORMATTER = 
             new SimpleDateFormat("yyyy-MM-dd HH:mm");
	
     /**
	 * 获取当前的时间的Data对象
	 * <br>Created 2014-8-22 下午8:16:15
	 * @return 当前的时间的Data对象
	 * @author       huangyx
	 */
	public static Date getNowTime(){
		Calendar calendar = Calendar.getInstance();
		Date nowDate = calendar.getTime();		
		return nowDate;
	}
	
	/**
     * 获取当前的时间
     * <br>Created 2014-8-22 下午8:16:15
     * @return 当前的时间
     * @author       huangyx
     */
	public static String getNowTimeStr(){
        return getMsgTime(getNowTime());
    }
	
	/**
	 * 把Date对象转成格式："yyyy-MM-dd HH:mm"的形式
	 * <br>Created 2014-8-22 下午8:17:45
	 * @return 对应的时间格式
	 * @author       huangyx
	 */
	public static SimpleDateFormat getChatSdf (){
		return otherChatSdf;
	}
	
	/**
	 * 把Date对象转成格式："MM-dd HH:mm"的形式
	 * <br>Created 2014-8-22 下午8:22:36
	 * @param date Date对象
	 * @return 对应的时间格式
	 * @author       huangyx
	 */
	public static String getMsgTime(Date date){
		if(date ==null) {
		    return "";
		} else {
		    synchronized (otherRecentSdf) {
		        return otherRecentSdf.format(date);
            }
		}
	}
	
	/**
	 * 把Date对象转成格式："yyyy-MM-dd HH:mm"或者"MM-dd HH:mm"的形式
	 * <br>Created 2014-8-22 下午8:23:44
	 * @param date Data对象
	 * @param type 0：转成"MM-dd HH:mm"，其他：转成"yyyy-MM-dd HH:mm"
	 * @return 时间格式
	 * @author       huangyx
	 */
	public static String getMsgHourFormatStr(Date date, int type){
		synchronized (todayRecentSdf) {
		    if(type == 0) {
		        return todayRecentSdf.format(date);
		    } else {
		        return todayRecentSdf.format(date);
		    }
        }
	}
	
	public static String getMsgYesterdayFormatStr(Date date, int type) {
		synchronized (yesterdayRecentSdf) {
		    if(type == 0) {
		        return yesterdayRecentSdf.format(date);
		    } else {
		        return yesterdayRecentSdf.format(date);
		    }
        }
	}
	
	public static String getMsgBeforeYesterdayFormatStr(Date date,int type){
	    synchronized (beforeYesterDayRecentSdf) {
	        if(type==0) {
	            return beforeYesterDayRecentSdf.format(date);
	        } else {
	            return beforeYesterDayRecentSdf.format(date);
	        }
	    }
	}
	
	/**
     * 把Date对象转成格式："MM-dd"的形式
     * <br>Created 2014-8-22 下午8:23:44
     * @param date Data对象
     * @return 时间格式
     * @author       huangyx
     */
	public static String getMsgMonthHourFormatStr(Date date){
	    synchronized (monthformat) {
	        return monthformat.format(date);
        }
	}
	
	/**
	 * 判断Date对象是今天还是昨天
	 * <br>Created 2014-8-22 下午8:33:14
	 * @param a Date对象
	 * @return 是今天返回1，否则返回0
	 * @author       huangyx
	 */
	public static int isTodayOrYesterDay(Date a) {
		Calendar c = Calendar.getInstance();
		Date today = c.getTime();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd" );
		if(format.format(today).equals(format.format(a))) {
		    return 1;
		}
		return 0;
	}
	
	/**
	 * 解析日期
	 * <br>Created 2014-8-27 下午2:49:38
	 * @param createTime 日期
	 * @param type 类型
	 * @return 解析后的日期
	 * @author       huangyx
	 */
    @SuppressWarnings("deprecation")
    public static String parseDate(Date createTime, int type){
        SimpleDateFormat datesdf1 = null;
		SimpleDateFormat datesdf2 = null;
		SimpleDateFormat datesdf3 = null;
		SimpleDateFormat datesdf4 = null;
		SimpleDateFormat datesdf5 = null;
		if(type == 0) {
			datesdf1 = todayRecentSdf;
			datesdf2 = yesterdayRecentSdf;
			datesdf3 = beforeYesterDayRecentSdf;
			datesdf4 = otherRecentSdf;
		 } else {
			datesdf1 = todayRecentSdf;
			datesdf2 = yesterdayRecentSdf;
			datesdf3 = beforeYesterDayRecentSdf;
			datesdf4 = otherChatSdf;
			datesdf5 = otherRecentSdf;
		 }
	     try {
	         String ret = "";
	         Calendar calendar = Calendar.getInstance();
	         calendar.setTime(createTime);
	         long create = calendar.getTimeInMillis();
	         Calendar now = Calendar.getInstance();
	         long ms = 1000 * (now.get(Calendar.HOUR_OF_DAY) * 3600 +
	                 now.get(Calendar.MINUTE) * 60 + now.get(Calendar.SECOND));//毫秒数
	         long ms_now = now.getTimeInMillis();
	         
	         if(ms_now - create < ms) {
	             synchronized (datesdf1) {
	                 ret = datesdf1.format(createTime);
	             }
	         }else if(ms_now - create < (ms + 24 * 3600 * 1000)) {
	             synchronized (datesdf2) {
                     ret = datesdf2.format(createTime);
                 }
	         }else if(ms_now - create < (ms + 24 * 3600 * 1000 * 2)){
	             synchronized (datesdf3) {
                     ret = datesdf3.format(createTime);
                 }
            } else if ((ms_now - create > (ms + 24 * 3600 * 1000 * 3))
                    && calendar.get(Calendar.YEAR) == now.get(Calendar.YEAR)) {
                synchronized (datesdf5) {
                    ret = datesdf5.format(createTime);
                }
             }else{
	             synchronized (datesdf4) {
                     ret = datesdf4.format(createTime);
                 }
	         }
	         return ret;
	         } catch (Exception e) {
	          	e.printStackTrace();
	          	return "";
	     }
	}
	 
    /**
     * date2超过date1在3分钟以上
     * <br>Created 2014-8-22 下午8:51:29
     * @param date1 Data对象1
     * @param date2 Data对象2
     * @return date2超过date1在3分钟以上或者其中之一为null返回true，否则返回false
     * @author       huangyx
     */
    public static boolean comparent(Date date1, Date date2){
        if(date1 == null || date2 == null) {
            return true;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date1);
        long time1 = calendar.getTimeInMillis();
        calendar.setTime(date2);
        long time2 = calendar.getTimeInMillis();
        return (time2 - time1) > 3 * 60 * 1000;
	}
 
    /**
     * 获取时间和当前时间的距离
     * 该方法是旧的逻辑方法，如果要删要通知其他模块非外链的项目
     * <br>Created 2014-4-11上午9:56:33
     * @param date Date对象
     * @return 时间和当前时间的距离
     * @author       huangyx
     */
    public static String getLastTime(Date date){
        Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		long diff = (System.currentTimeMillis() - cal.getTimeInMillis()) / 1000;
		 
		if(diff == 0){
			return "刚刚";
		}
		if(diff > 0 && diff < 60){
			return diff + "秒前";
		} else if(diff >= 60 && diff < 60 * 60){
		    return "约" + diff / 60 + "分钟前";
		} else {
		    return parseDate(date, 1);
		}
	}
	 
    /**
     * 获取时间和当前时间的距离
     * 该方法是旧的逻辑方法，如果要删要通知其他模块非外链的项目
     * <br>Created 2014-4-11上午9:56:33
     * @param timeMillis 毫秒
     * @return 时间和当前时间的距离
     * @author       huangyx
     */
	public static String getLastTime(long timeMillis) {
		Date date = new Date(timeMillis);
		return getLastTime(date);
	}
	 
	/**
	 * 1.时间显示：当天显示小时、分钟；2.一周内显示星期几；3.一周外显示日期（月、天）；4.一年外显示年、月、日
	 * <br>Created 2014-3-12 下午4:04:55
	 * @param timeMillis 要显示的时间，毫秒为单位
	 * @param showTime true表示任何条件下都需要显示时：分  false表示不需要
	 * @return 时间显示形式
	 * @author       huangyx
	 */
	public static String getVTLastTime(long timeMillis, boolean showTime) {
	    Date date = new Date(timeMillis);
	    return getVTLastTime(date, showTime);
	}
	
	/**
     * 1.时间显示：当天显示小时、分钟；2.一周内显示星期几；3.一周外显示日期（月、天）；4.一年外显示年、月、日
     * <br>Created 2014-3-12 下午4:01:55
     * @param date 要显示的时间date对象
     * @param showTime true表示任何条件下都需要显示时：分  false表示不需要
     * @return 时间显示形式
     * @author       huangyx
     */
	public static String getVTLastTime(Date date, boolean showTime) {
		StringBuilder sb = new StringBuilder();
		long now = System.currentTimeMillis();
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		Calendar calnow = Calendar.getInstance();
		calnow.setTimeInMillis(now);

		// 当天
		if (cal.get(Calendar.YEAR) == calnow.get(Calendar.YEAR)
				&& cal.get(Calendar.MONTH) == calnow.get(Calendar.MONTH)
				&& cal.get(Calendar.DAY_OF_MONTH) == calnow
						.get(Calendar.DAY_OF_MONTH)) {
			sb.append(String.format(
					ApplicationVariable.INSTANCE.applicationContext.getString(
							R.string.hhmm), cal.get(Calendar.HOUR_OF_DAY), cal
							.get(Calendar.MINUTE)));
		} else {
			// 设置昨天开始时间
			Calendar yesterBegin = Calendar.getInstance();
			yesterBegin.setTimeInMillis(now);
			yesterBegin.set(Calendar.HOUR_OF_DAY, 0);
			yesterBegin.set(Calendar.MINUTE, 0);
			yesterBegin.set(Calendar.SECOND, 0);
			yesterBegin.add(Calendar.DAY_OF_YEAR, -1);

			// 设置昨天结束时间
			Calendar yesterEnd = Calendar.getInstance();
			yesterEnd.setTimeInMillis(now);
			yesterEnd.set(Calendar.HOUR_OF_DAY, 23);
			yesterEnd.set(Calendar.MINUTE, 59);
			yesterEnd.set(Calendar.SECOND, 59);
			yesterEnd.add(Calendar.DAY_OF_YEAR, -1);

			// 昨天
			if (cal.getTimeInMillis() >= yesterBegin.getTimeInMillis()
					&& cal.getTimeInMillis() < yesterEnd.getTimeInMillis()) {
				sb.append(ApplicationVariable.INSTANCE.applicationContext.getString(R.string.yesterday));
			} else {
				yesterBegin.add(Calendar.DAY_OF_YEAR, -5);
				// 一周内
				if (cal.getTimeInMillis() >= yesterBegin.getTimeInMillis()
						&& cal.getTimeInMillis() < yesterEnd.getTimeInMillis()) {
					sb.append(getWeekDescription(cal.get(Calendar.DAY_OF_WEEK) - 1));
				} else {
					// 同年，不显示年份，否则显示
					if (cal.get(Calendar.YEAR) == calnow.get(Calendar.YEAR)) {
						sb.append(String.format(
								ApplicationVariable.INSTANCE.applicationContext
										.getString(R.string.mmdd), cal
										.get(Calendar.MONTH) + 1, cal
										.get(Calendar.DAY_OF_MONTH)));
					} else {
						sb.append(String.format(
								ApplicationVariable.INSTANCE.applicationContext
										.getString(R.string.yymmdd), cal
										.get(Calendar.YEAR), cal
										.get(Calendar.MONTH) + 1, cal
										.get(Calendar.DAY_OF_MONTH)));
					}
				}
			}
			if(showTime){
				sb.append(" ").append(String.format(
						ApplicationVariable.INSTANCE.applicationContext.getString(
								R.string.hhmm), cal.get(Calendar.HOUR_OF_DAY), cal
								.get(Calendar.MINUTE)));
			}
		}
		return sb.toString();
	}
	
	/**
	 * 根据dayofweek获取实际星期几
	 * 注意：1表示星期1，2表示星期2，以此类推
	 * <br>Created 2014-3-11 下午7:18:33
	 * @param dayofweek 数字型的星期几
	 * @return 实际星期几
	 * @author       huangyx
	 */
	public static String getWeekDescription(int dayofweek){
		Context ctx = ApplicationVariable.INSTANCE.applicationContext;
		int resId = 0;
		switch(dayofweek){
		case 1:
			resId = R.string.monday;
			break;
		case 2:
			resId = R.string.tuesday;
			break;
		case 3:
			resId = R.string.wednesday;
			break;
		case 4:
			resId = R.string.thursday;
			break;
		case 5:
			resId = R.string.friday;
			break;
		case 6:
			resId = R.string.saturday;
			break;
		case 7:
			resId = R.string.sunday;
			break;
			default:
				resId = R.string.sunday;
				break;
				
		}
		return ctx.getString(resId);
	}
	 
	/**
	 * 把时间转换成yyyy-mm-dd 或者 mm-dd
	 * <br>Created 2014-8-22 下午9:04:37
	 * @param timestamp 时间，毫秒为单位
	 * @return 时间格式：yyyy-mm-dd 或者 mm-dd
	 * @author       huangyx
	 */
    public static String formateMillisTime(long timestamp) {
    	int currentYear = Calendar.getInstance().get(Calendar.YEAR);
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTimeInMillis(timestamp);
    	int year = calendar.get(Calendar.YEAR);
    	
    	if (currentYear > year) { // yyyy-mm-dd
    		return DateFormat.format("yyyy-MM-dd", timestamp).toString(); 
    	} else { // mm-dd
    		return DateFormat.format("MM-dd", timestamp).toString(); 
    	}
    }
    
    /**
     * 把时间转换成yyyy-mm-dd 或者 mm-dd
     * <br>Created 2014-8-22 下午9:05:52
     * @param timestamp 时间，秒为单位
     * @return 时间格式：yyyy-mm-dd 或者 mm-dd
     * @author       huangyx
     */
    public static String formateEpochTime(long timestamp) {
    	return formateMillisTime(timestamp * 1000);
    }

    /**
     * 判断给定时间是今天、昨天还是其他
     * <br>Created 2014-8-25 上午9:40:51
     * @param anchor 给定的时间
     * @return 给定时间的时间类型是今天、昨天还是其他
     * @author       huangyx
     */
    static public String getDateString(long anchor) {

        StringBuffer sb = new StringBuffer("");
        long now = System.currentTimeMillis();
        long aday = 24 * 60 * 60 * 1000;
        long yesterday = now - aday;

        String todayDate = getDate(now);
        String yesterdayDate = getDate(yesterday);
        String anchorDate = getDate(anchor);

        if (anchorDate.equals(todayDate)) {
            sb.append("今天");
        } else if (anchorDate.equals(yesterdayDate)) {
            sb.append("昨天");
        } else {
            sb.append(anchorDate);
        }

        sb.append(" ");

        String time = getTime(anchor);
        sb.append(time);

        return sb.toString();
    }

    /**
     * 将毫秒为单位的时间转换为格式yyyy-MM-dd
     * <br>Created 2014-8-25 上午9:44:39
     * @param date 毫秒为单位的时间
     * @return yyyy-MM-dd格式的时间
     * @author       huangyx
     */
    static public String getDate(long date) {
        CharSequence val = DateFormat.format("yyyy-MM-dd", new Date(date));
        return val.toString();
    }
    
    /**
     * 将毫秒为单位的时间转换为格式k:mm
     * <br>Created 2014-8-25 上午9:48:39
     * @param date 毫秒为单位的时间
     * @return k:mm格式的时间
     * @author       huangyx
     */
    static public String getTime(long date) {
        CharSequence val = DateFormat.format("k:mm", new Date(date));
        return val.toString();
    }
    
    /**
     * 将毫秒为单位的时间转换为格式yyyy-MM-dd k:mm:ss
     * <br>Created 2014-8-25 上午9:55:39
     * @param date 毫秒为单位的时间
     * @return yyyy-MM-dd k:mm:ss格式的时间
     * @author       huangyx
     */
    public static String getFullTime(long date) {
        CharSequence val = DateFormat.format("yyyy-MM-dd k:mm:ss", new Date(date));
        return val.toString();
    }

    /**
     * 将毫秒为单位的时间差转化为几小时几分几秒格式
     * <br>Created 2014-8-25 上午9:54:10
     * @param nDuration 毫秒为单位的时间差
     * @return 几小时几分几秒格式的时间
     * @author       huangyx
     */
    static public String getDurationString(int nDuration) {
        int nHour = 0;
        int nMin = 0;
        int nSec = 0;

        nHour = nDuration / 3600;
        nMin = nDuration / 60;
        nSec = nDuration % 60;

        StringBuffer strTime = new StringBuffer("");

        if (nHour != 0) {
            strTime.append(nHour);
            strTime.append(" 小时 ");
        }

        strTime.append(nMin);
        strTime.append(" 分钟 ");

        strTime.append(nSec);
        strTime.append(" 秒 ");

        return strTime.toString();
    }
    
    /**
     * 将YYYY-MM-DD格式的日期转换成Unix时间戳
     * <br>Created 2014-8-25 上午9:56:24
     * @param date YYYY-MM-DD格式的日期
     * @return Unix时间戳
     * @author       huangyx
     */
    @SuppressWarnings("deprecation")
    static public long getTimeStamp(String date) {
        if (null == date || date.length() < 1) {
            return 0;
        }
        String arrDate[] = date.split("-");
        if (arrDate.length == 3) {
            return Date.UTC(Integer.valueOf(arrDate[0]) - 1900,
                    Integer.valueOf(arrDate[1]) - 1,
                    Integer.valueOf(arrDate[2]), 0, 0, 0);

        } else if (arrDate.length == 2) {
            return Date.UTC(0,
                    Integer.valueOf(arrDate[0]) - 1,
                    Integer.valueOf(arrDate[1]), 0, 0, 0);
        }
        return 0;
    }

    /**
     * 判断以毫秒为单位的时间是今天、昨天、前天还是上周
     * <br>Created 2014-8-25 上午9:58:57
     * @param timeStamp 毫秒为单位的时间
     * @return 时间是今天、昨天、前天还是上周
     * @author       huangyx
     */    
    public static String getTimePeriod(long timeStamp) {
        
        long tempTime;
        if (timeStamp < 10000000000L) {
            tempTime = timeStamp * 1000;
        } else {
            tempTime = timeStamp;
        }
        long now = System.currentTimeMillis();

        long aday = 24 * 60 * 60 * 1000;
        long yesterday = now - aday;
        long beforeYesterday = now - aday * 2;
        long week = now - aday * 6;

        String todayDate = getDate(now);
        String yesterdayDate = getDate(yesterday);
        String beforeYesterdayDate = getDate(beforeYesterday);
        String weekDate = getDate(week);
        long weekTime = getTimeStamp(weekDate);
        String anchorDate = getDate(tempTime);
        String format = "MM-dd HH:mm";
        String prefix = "";
        if (anchorDate.equals(todayDate)) {
            format = "HH:mm";
        } else if (now - tempTime >= 0) {
            if (anchorDate.equals(yesterdayDate)) {
                format = "HH:mm";
                prefix = "昨天";
            } else if (anchorDate.equals(beforeYesterdayDate)) {
                format = "HH:mm";
                prefix = "前天";
            } else if (tempTime > weekTime) {
                format = "E HH:mm";
            }
        }
        return prefix + getTimeFormat(
                format,
                tempTime
                        + TimeZone.getTimeZone("GMT+8:00 ").getRawOffset()
                        - TimeZone.getDefault().getRawOffset());
    }

    /**
     * 将以毫秒为单位的时间转换成指定格式
     * <br>Created 2014-8-25 上午10:10:24
     * @param format 时间格式
     * @param time  定以毫秒为单位的时间
     * @return 时间格式
     * @author       huangyx
     */
    public static String getTimeFormat(String format, long time) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        Date curDate = new Date(time);// 获取当前时间
        return formatter.format(curDate);
    }
    
    /**
     * 将指定日期转化为格式yyyy-MM-dd HH:mm:ss
     * <br>Created 2014-8-25 上午10:14:54 
     * @param date 指定日期
     * @return 格式yyyy-MM-dd HH:mm:ss日期
     * @author       huangyx 
     */
    public static String getDateTime(Date date) {
        if (date == null) {
            return "";
        }
        String strTime = null;
        try {
            SimpleDateFormat objMyformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            strTime = objMyformat.format(date);
        } catch (Exception e) {
            System.out.println("CommUtil.getCurrentDateTime" + e);
        }
        return strTime;
    }
    
    /**
     * 获取当前日期，格式为yyyy-MM-dd HH:mm:ss
     * <br>Created 2014-8-25 上午10:18:54 
     * @return 格式为yyyy-MM-dd HH:mm:ss的日期
     * @author       huangyx 
     */
    public static String getCurrentDateTime() {
        String strTime = null;
        try {
            SimpleDateFormat objMyformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            strTime = objMyformat.format(new Date());
        } catch (Exception e) {
            System.out.println("CommUtil.getCurrentDateTime" + e);
        }
        return strTime;
    }
    
    /**
     * 获取当前日期，格式为yyyy-MM-dd
     * <br>Created 2014-8-25 上午10:22:54 
     * @return 格式yyyy-MM-dd的日期
     * @author       huangyx 
     */
    public static String getCurrentDate() {
        String strTime = null;
        try {
            SimpleDateFormat objMyformat = new SimpleDateFormat("yyyy-MM-dd");
            strTime = objMyformat.format(new Date());
        } catch (Exception e) {
            System.out.println("CommUtil.getCurrentDateTime" + e);
        }
        return strTime;
    }

    /**
     * 返回当前时间,格式HH:mm
     * <br>Created 2014-8-21 下午3:47:26
     * @param date 日期
     * @return 当前时间
     * @author       huangyx  
     */
    public static String getCurrentTime(Date date) {
        String time = "";
        try {
            SimpleDateFormat myformat = new SimpleDateFormat("HH:mm");
            time = myformat.format(date);
        } catch (Exception e) {
            System.out.println(e);
        }
        return time;
    }
    
    /**
     * 返回当前时间
     * <br>Created 2014-8-25 下午9:20:02
     * @return 当前时间
     * @author       huangyx
     */
    public static long getCurrentTime() {
        return Calendar.getInstance().getTime().getTime();
    }
    
    /**
     * 从gid中获取时间
     * <br>Created 2013-11-13下午3:54:29
     * @param guid 
     * @return 时间
     * @author       zhy
     */
    public static String getcurrentTimeMillis(String guid) {
        if (StringUtils.isBlank(guid)) {
            return null;
        }
        int index = guid.indexOf("-");
        if (index != -1) {
            return guid.substring(0, index);
        } else {
            return null;
        }
    }
    
    /**
     * 指定日期如果是今天则转换成格式为HH:MM，否则转化为yyyy-MM-dd格式日期
     * <br>Created 2014-8-25 上午10:27:54
     * @param date 指定日期
     * @return 如果是今天则转换成格式为HH:MM，否则转化为yyyy-MM-dd格式日期
     * @author       huangyx 
     */
    public static String getDate(Date date) {
        if (date == null) {
            return "";
        }
        String strTime = "";
        try {
            if (getDayDiffFromToday(date)) { // 如果是今天
                strTime = getCurrentTime(date);
            } else {
                SimpleDateFormat objMyformat = new SimpleDateFormat("yyyy-MM-dd");
                strTime = objMyformat.format(date);
            }
        } catch (Exception e) {
            strTime = "";
        }
        return strTime;
    }
    
    /**
     * 将以毫秒为单位的时间转换成GMT+8:00时区的Data对象
     * <br>Created 2014-8-25 上午10:36:06
     * @param timeStamp 毫秒为单位的时间
     * @return GMT+8:00时区的Data对象
     * @author       huangyx
     */
    public static Date getDate(Long timeStamp) {
        long temp = timeStamp;
        if (timeStamp < 10000000000L) {
            temp = timeStamp * 1000;
        } 
        long time = temp + TimeZone.getTimeZone("GMT+8:00 ").getRawOffset()
                - TimeZone.getDefault().getRawOffset();
        Date curDate = new Date(time);// 获取当前时间
        return curDate;
    }
    
    /**
     * 将以毫秒为单位的时间转换成GMT+8:00时区日期
     * <br>Created 2014-8-25 下午4:56:24
     * @param timeStamp 毫秒为单位的时间
     * @return GMT+8:00时区日期
     * @author       huangyx
     */
    public static String getTimeGMT8(long timeStamp) {
        long temp = timeStamp;
        if (timeStamp < 10000000000L) {
            temp = timeStamp * 1000;
        } 
        String time= TimeUtils.getTimeFormat(
                "yyyy-MM-dd HH:mm",  
                temp + TimeZone.getTimeZone("GMT+8:00 ").getRawOffset()
                     - TimeZone.getDefault().getRawOffset());
        if((time != null) && (time.indexOf(TimeUtils.getCurrentYear())!=-1)){
            time = time.substring(5);
        }
        return time;
    }
    
    /**
     * 判断以毫秒为单位的指定时间endtime距离date对象时间还有多久
     * <br>Created  2014-8-25 上午10:18:54
     * @param date date对象
     * @param endtime 以毫秒为单位的指定时间
     * @return 时间差
     * @author       huangyx     
     */
    public static String getDuration(Date date, long endtime) {
        if (date == null) {
            return "";
        }
        int durationSeconds = (int) Math
                .ceil((endtime - date.getTime()) * 1.0 / 1000);
        int hours = durationSeconds / (60 * 60);
        int leftSeconds = durationSeconds % (60 * 60);
        int minutes = leftSeconds / 60;
        int seconds = leftSeconds % 60;

        StringBuffer sBuffer = new StringBuffer();
        if (hours > 0) {
            sBuffer.append(addZeroPrefix(hours));
            sBuffer.append(":");
        }
        sBuffer.append(addZeroPrefix(minutes));
        sBuffer.append(":");
        sBuffer.append(addZeroPrefix(seconds));
        return sBuffer.toString();
    }

    /**
     * 如果number为个位数则前面0
     * <br>Created 2014-8-25 上午10:53:10
     * @param number 整型数值
     * @return 如果number为个位数则前面0，否则返回原number
     * @author       huangyx
     */
    public static String addZeroPrefix(int number) {
        if (number < 10) {
            return "0" + number;
        } else {
            return "" + number;
        }
    }
    
    /**
     * 获取startTime和endTime以秒为单位的时间差。
     * <br>Created 2014-8-25 上午10:55:10
     * @param startTime 以毫秒为单位的开始时间
     * @param endTime 以毫秒为单位的结束时间
     * @return 以秒为单位的时间差
     * @author       huangyx 
     */
    public static String getSeconds(long startTime, long endTime) {
        return FormatUtils.formatDoubleNumber((startTime - endTime) / 1000.0, 2);
    }

    /**
     * 将以秒为单位的时间转换成mm:ss格式
     * <br>Created 2014-8-25 上午11:01:18
     * @param totalCount 以秒为单位的时间 
     * @return mm:ss格式的时间
     * @author       huangyx
     */
    public static String getShowTime(int totalCount) {
        if (totalCount == 0) {
            return "00:00";
        }
        StringBuffer showtime = new StringBuffer();
        if (totalCount % 60 < 10 && totalCount / 60 < 10) {
            showtime.append("0");
            showtime.append(totalCount / 60);
            showtime.append(":0");
            showtime.append(totalCount % 60);
            // showtime.append("0"+(totalcount/60)+":"+"0"+(totalcount%60));
        } else if (totalCount % 60 > 9 && totalCount / 60 < 10) {
            showtime.append("0");
            showtime.append(totalCount / 60);
            showtime.append(":");
            showtime.append(totalCount % 60);
            // showtime.append("0"+(totalcount/60)+":"+(totalcount%60));
        } else if (totalCount % 60 < 10 && totalCount / 60 > 9) {
            showtime.append(totalCount / 60);
            showtime.append(":0");
            showtime.append(totalCount % 60);
            // showtime.append((totalcount/60)+":"+"0"+(totalcount%60));
        } else {
            showtime.append(totalCount / 60);
            showtime.append(":");
            showtime.append(totalCount % 60);
            // showtime.append((totalcount/60)+":"+(totalcount%60));
        }
        return showtime.toString();
    }

    /**
     * 判断给定日期是否为当天
     * <br>Created 2014-8-25 上午11:11:18 
     * @param dt 给定日期的date对象
     * @return 给定日期为当天返回true，否则返回false
     * @author       huangyx      
     */
    @SuppressWarnings("deprecation")
    public static boolean getDayDiffFromToday(Date dt) {
        Date today = new Date();
        today.setHours(23);
        today.setMinutes(59);
        today.setSeconds(59);

        long diff = today.getTime() - dt.getTime();
        if (diff < 0) {
            diff = 0;
        }
        long days = diff / (1000 * 60 * 60 * 24);
        if (days == 0) {
            return true;
        }
        return false;
    }
    
    /**
     * 获取int类型的当前年份
     * <br>Created 2014-8-25 上午11:16:18
     * @param dateStr String类型的当前年份字符串 
     * @return 当前年份
     * @author       huangyx       
     */
    public static int getYear(String dateStr) {
        if (dateStr == null || dateStr.length() < 4) {
            return FormatUtils.parseInt(getCurrentYear());
        }
        String year = dateStr.substring(0, 4);
        return FormatUtils.parseInt(year);
    }

    /**
     * 取出日期时间中的日期
     * <br>Created 2014-8-25 上午11:19:18
     * @param dt 时间日期 "YYYY-MM-DD HH:mm:ss"
     * @return 日期 YYYY-MM-DD
     * @author       huangyx       
     */
    public static String getDateOfDT(String dt) {
        String date = "";
        if (!StringUtils.isBlank(dt)) {
            if (dt.length() <= 10) {
                date = dt;
            } else {
                date = dt.substring(0, 10);
            }
        }
        return date;
    }

    /**
     * 返回日期的月
     * <br>Created 2014-8-25 上午11:21:18
     * @param dateStr 输入的字符串 格式YYYY-MM-DD
     * @return  月份
     * @author       huangyx       
     */
    public static int getMonth(String dateStr) {
        if (dateStr == null || dateStr.length() < 7) {
            return getCurrentMonth();
        }
        String month = dateStr.substring(5, 7);
        LogUtils.v(TAG, "month :" + FormatUtils.parseInt(month));
        return FormatUtils.parseInt(month);
    }
     
    /**
     * 返回当前年 格式YYYY
     * <br>Created  2014-8-25 上午11:25:18
     * @return 年份
     * @author       huangyx    
     */
    public static String getCurrentYear() {
        String year = null;
        try {
            SimpleDateFormat myformat = new SimpleDateFormat("yyyy-MM-dd");
            String date = myformat.format(new Date());
            year = date.substring(0, 4);
        } catch (Exception e) {
            System.out.println(e);
        }
        return year;
    }

    /**
     * 返回当前月份
     * <br>Created 2014-8-21 下午4:00:39
     * @return 月份
     * @author       huangyx 
     */
    public static int getCurrentMonth() {
        int month = 12;
        try {
            SimpleDateFormat myformat = new SimpleDateFormat("yyyy-MM-dd");
            String date = myformat.format(new Date());
            month = FormatUtils.parseInt(date.substring(5, 7));
        } catch (Exception e) {
            System.out.println(e);
        }
        return month;
    }

    /**
     * 返回当前的日
     * <br>Created 2014-8-25 上午11:27:18 
     * @return 日
     * @author       huangyx 
     */
    public static int getCurrentDay() {
        int day = 0;
        try {
            SimpleDateFormat myformat = new SimpleDateFormat("yyyy-MM-dd");
            String date = myformat.format(new Date());
            day = FormatUtils.parseInt(date.substring(8, 10));
        } catch (Exception e) {
            System.out.println(e);
        }
        return day;
    }

    /**
     * 判断hourOfDay是早上还是下午
     * <br>Created 2014-8-25 上午11:29:56
     * @param hourOfDay 小时
     * @param minute 分钟
     * @return 加上AM或者PM的时间
     * @author       huangyx
     */
    public static String getHourMinute(int hourOfDay, int minute) {
        StringBuffer rec = new StringBuffer();
        String s="";
        switch (hourOfDay / 6) {
        case 0:
        case 1:
            s=" AM";
            break;
        case 2:
        case 3:     
            if(hourOfDay != 12){
                hourOfDay=hourOfDay - 12;
            }
            s=" PM";
            break;
        default:
            break;
        }
        if(hourOfDay==0){
            hourOfDay=12;
        }
        rec.append(addZeroPrefix(hourOfDay));
        rec.append(":");
        rec.append(addZeroPrefix(minute));
        rec.append(s);
        return rec.toString();
    }

    /**
     * 检查当前时间是否位于两个时间之前，使用12小时制
     * <br>Created  2014-8-25 上午11:29:18
     * @param hour1     开始时间小时
     * @param minute1   开始时间分钟
     * @param hour2     结束时间小时
     * @param minute2   结束时间分钟
     * @return 是否位于两个小时之间
     * @author       huangyx  
     */
    @SuppressWarnings("deprecation")
    public static boolean isBetweenPeriod(int hour1, int minute1, int hour2,
            int minute2) {
        if(hour1==0){
            hour1=12;
        }else if(hour1==12){
            hour1=0;
        }
        if(hour2==0){
            hour2=12;
        }else if(hour2==12){
            hour2=0;
        }
        Date date = new Date();
        int src = date.getHours() * 60 + date.getMinutes();
        int time1 = hour1 * 60 + minute1;
        int time2 = hour2 * 60 + minute2;
//       Log.v(TAG,"hour1:"+hour1 +" hour2:"+hour2+" date.getHours():"+date.getHours());
//       Log.v(TAG,"src:"+src +" time1:"+time1 +" time2:"+time2);
        if (time2 > time1) {
            return src >= time1 & time2 >= src;
        } else {
            return time1 == time2;
        }
    }
    
    /**
     * 检查当前时间是否位于两个时间之前，使用24小时制
     * <br>Created 2014-5-14 下午11:43:48
     * @param hour1     开始时间小时
     * @param minute1   开始时间分钟
     * @param hour2     结束时间小时
     * @param minute2   结束时间分钟
     * @return 是否位于两个小时之间
     * @author linsj
     */
    @SuppressWarnings("deprecation")
    public static boolean isBetweenPeriodEx(int hour1, int minute1, int hour2,
            int minute2) {
        // 取得时间所代表的分钟数
        int iMinuteCount1 = hour1 * 60 + minute1;
        int iMinuteCount2 = hour2 * 60 + minute2;

        // 取得当前时间
        Date date = new Date();
        int iCurMinutePast = date.getHours() * 60 + date.getMinutes();

        // 如果两个时间相等，就是全天候啦
        if (iMinuteCount2 == iMinuteCount1) {
            return true;
        }

        // 如果结束时间小于开始时间，说明是第二天，要加上一天
        if (iMinuteCount2 < iMinuteCount1) {
            iMinuteCount2 += 24 * 60;
        }

        // 如果当前时间位于开始时间与结束时间之前
        if (iCurMinutePast > iMinuteCount1 && iMinuteCount2 > iCurMinutePast) {
            return true;
        }

        return false;
    }

    /**
     * date时间和当前时间的差值是否大于outTimeSecond
     * <br>Created 2014-8-25 上午11:33:18
     * @param date 作为减数的Date对象
     * @param outTimeSecond 时间差值，秒为单位
     * @return date时间和当前时间的差值是否大于outTimeSecond返回true，否则返回false
     * @author       huangyx        
     */
    public static boolean getSecondTween(String date, int outTimeSecond) {
        long mill1 = System.currentTimeMillis();
        long mill2 = Long.parseLong(date);
        if ((int) ((mill1 - mill2) / (1000)) >= outTimeSecond) {
            return true;
        }
        return false;
    }
    /**
     * 返回两个Date对象的之间的分钟数差值
     * <br>Created 2014-8-25 上午11:35:18 
     * @param date1 作为被减数的Date对象
     * @param date2 作为减数的Date对象
     * @return 两个Date对象的之间的分钟数差值
     * @author       huangyx  
     */
    public static int getMinutesTween(Date date1, Date date2) {
        long mill1 = date1.getTime();
        long mill2 = date2.getTime();
        return (int) Math.ceil((mill1 - mill2) * 1.0 / (1000 * 60));
    }
    
    /**
     * 返回两个long对象的之间的分钟数差值
     * <br>Created  2014-8-25 上午11:38:18
     * @param mill1 作为被减数的long对象
     * @param mill2 作为减数的long对象
     * @return 两个long对象的之间的分钟数差值
     * @author       huangyx  
     */
    public static int getMinutesTween(long mill1, long mill2) {
        return (int) Math.ceil((mill1 - mill2) * 1.0 / (1000 * 60));
    }

    /**
     * 返回两个long对象的之间的秒数差值
     * <br>Created 2014-8-25 上午11:40:18
     * @param mill1 作为被减数的long对象
     * @param mill2 作为减数的long对象
     * @return 两个long对象的之间的秒数差值
     * @author       huangyx       
     */
    public static int getSecondsTween(long mill1, long mill2) {
        return (int) Math.ceil((mill1 - mill2) * 1.0 / 1000);
    }
    
    /**
     * 解析时间
     * <br>Created 2014-8-25 下午9:10:24
     * @param dateString 时间
     * @return 解析后的时间
     * @author       huangyx
     */
    public static final Date parseDateTime(String dateString) {
        try {
            synchronized (TWITTER_DATE_FORMATTER) {
                return TWITTER_DATE_FORMATTER.parse(dateString);
            }
        } catch (ParseException e) {
            LogUtils.w(TAG, "Could not parse Twitter date string: " + dateString);
          return new Date(System.currentTimeMillis());
        }
    }

    /**
     * 从sqlite数据库解析时间
     * <br>Created 2014-8-25 下午9:11:17
     * @param dateString 时间
     * @return 解析的时间
     * @author       huangyx
     */
    public static final Date parseDateTimeFromSqlite(String dateString) {
        try {
            synchronized (DB_DATE_FORMATTER) {
                return DB_DATE_FORMATTER.parse(dateString);
            }
        } catch (ParseException e) {
            LogUtils.w(TAG, "Could not parse Twitter date string: " + dateString);
          return new Date(System.currentTimeMillis());
        }
    }

    /**
     * 将字符串转换为时间
     * <br>Created 2014-8-25 下午9:17:46
     * @param dateString 时间
     * @return Data对象的时间
     * @author       huangyx
     */
    public static final Date parseSearchApiDateTime(String dateString) {
        try {
            synchronized (TWITTER_SEARCH_API_DATE_FORMATTER) {
                return TWITTER_SEARCH_API_DATE_FORMATTER.parse(dateString);
            }
        } catch (ParseException e) {
            LogUtils.w(TAG, "Could not parse Twitter search date string: "
                    + dateString);
          return new Date(System.currentTimeMillis());
        }
    }
    
    /**
     * 获取上个星期X的日期
     * <br>Created 2014-8-25 下午9:20:35
     * @param dayOfWeek  取上个礼拜的周几。如Calendar.MONDAY
     * @return 上个星期X的日期
     * @author       huangyx
     */
    public static Date getLastWeekDay(int dayOfWeek){
        
        Calendar calendar = Calendar.getInstance();
        // 默认从星期天开始算，在中国要从周一算起
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        // 获取的是上个星期，so减去1个星期的时间
        calendar.roll(Calendar.WEEK_OF_YEAR, -1);
        
        calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
        
        return calendar.getTime();
    }
    
    /**
     * 转为指定格式的日期
     * <br>Created 2014-8-25 下午9:21:12
     * @param date 日期
     * @param format 格式
     * @return 指定格式的日期
     * @author       huangyx
     */
    public static String formatDate(Date date,SimpleDateFormat format){
        
        return format.format(date);
    }
    
    /**
     * 获取上周日期的字符串
     * <br>Created 2014-8-25 下午9:21:48
     * @return 例如，2013年10月7日～10月13日  如果跨年就显示2013年12月30日～2014年1月6日
     * @author       huangyx
     */
    @SuppressWarnings("deprecation")
    public static String getLastWeekStr(){
        Date monday = getLastWeekDay(Calendar.MONDAY);
        Date sunday = getLastWeekDay(Calendar.SUNDAY);
        boolean sameYear = false;
        if (monday.getYear() == sunday.getYear()) {
            sameYear = true;
        }
        
        String mondayStr = formatDate(monday, DATE_FORMATTER_YMD);
        String sundayStr = formatDate(sunday, DATE_FORMATTER_YMD);
        if (sameYear) {
            return mondayStr + "～" + sundayStr.substring(5);
        } else {
            return mondayStr + "～" + sundayStr;
        }
    }
     
    /**
     * 计算2天的相差天数
     * <br>Created 2014-8-25 下午9:22:24
     * @param birthday 生日日期
     * @param today 今天日期
     * @return 计算2天的相差天数
     * @author       huangyx
     */
    
    public static int getDayBetween(String birthday, Date today) {
        
        synchronized (BIRTHDATE_FORMATTER) {
            try {
                
                Date date = BIRTHDATE_FORMATTER.parse(birthday);
                return (int) ((date.getTime() - today.getTime()) / ONEDAY_SECONDSMillis);
            } catch (ParseException e) {
                e.printStackTrace();
                return 0;
            } 
        }
    }
        
    /**
     * 通过生日获取年龄
     * <br>Created 2014-8-25 下午9:23:44
     * @param birthday 生日日期
     * @return 年龄
     * @author       huangyx
     */
    @SuppressWarnings("deprecation")
    public static String getAgeByBirthday(String birthday){
        
        if (TextUtils.isEmpty(birthday) || birthday.equals("0000-00-00")) {
            return "-";
        }
        
        long l = 0;
        Pattern pattern = Pattern.compile("//^[\\d]{4}[-\\ ][\\d]{1,2}[-\\ ][\\d]{1,2}$//");
        if(pattern.matcher(birthday).matches()){
            return "-";
        }
        
        try{
            l = Date.parse(birthday.replace("-","/"));
        } catch(RuntimeException e) {
            return "-";
        }
        
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        int year1 = date.getYear() ;
        int month1 = date.getMonth();
        int day1 = date.getDate();
        
        calendar.setTimeInMillis(l);
        date = calendar.getTime();
        
        int year2 = date.getYear();
        int month2 = date.getMonth();
        int day2 = date.getDate();
        
        int yearDiff = year1-year2;
        int monthDiff = month1 - month2;
        if (day1 - day2 < 0) {
            monthDiff = monthDiff - 1;
        }
        if (monthDiff < 0) {
            yearDiff = yearDiff - 1; 
        }
        if (yearDiff > 0) {
            return String.valueOf(yearDiff);
        } else {
            return "0";
        }
    }
    
    /**
     * 生成随机数
     * 
     * <br>Created 2014-10-20 下午4:55:47
     * @return
     * @author       huangyx
     */
    public static long generateLong(){
        return  System.currentTimeMillis()*new Random().nextInt(10000);
    }
    
}